<script type="text/javascript">
	$(document).ready(function() {
		document.title = "Aplicação do Algoritmo GARP para Dados de Espécies";

		// botão Voltar: retorna à página Home
		$('#back').click(function() {
			$.ajax({
				type:   'POST',
				url:    "HomeContent.php",
				data:   {},
				success: function(response) {
					$('#application').hide();
					$('#application').html("");
					$('#header').show();
					$('#wrapper').show();
					$('#footer').show();
					$('#content').html(response);
				},
				error: function(message){
					$('#content').html(message);
				}
			});
			return false;
		});

		// gera os mapas da aplicação requisitada após o algoritmo ser executado
		generateMaps();
	});

	function generateMaps() {
		OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
		OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
		OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
		var map;
		var options = {
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
			// map horizontal units are meters
			units: "m",
			// this resolution displays the globe in one 256x256 pixel tile
			maxResolution: 156543.0339,
			// these are the bounds of the globe in sperical mercator
			maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
			20037508, 20037508),
			controls: [new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar()]
		};
		map = new OpenLayers.Map('map',options);
		map.addControl(new OpenLayers.Control.LayerSwitcher());

		// cria as Layers do Google Maps
		var gphy = new OpenLayers.Layer.Google(
			"Google Physical",
			{type: G_PHYSICAL_MAP,'sphericalMercator': true}
		);
		var gmap = new OpenLayers.Layer.Google(
			"Google Street", // the default
			{'sphericalMercator': true}
		);
		var ghyb = new OpenLayers.Layer.Google(
			"Google Hybrid",
			{type: G_HYBRID_MAP,'sphericalMercator': true}
		);
		var gsat = new OpenLayers.Layer.Google(
			"Google Satellite",
			{type: G_SATELLITE_MAP,'sphericalMercator': true}
		);

		// cria as Layers do Yahoo! Maps
		var yahoo = new OpenLayers.Layer.Yahoo(
			"Yahoo Street",
			{'sphericalMercator': true}
		);
		var yahoosat = new OpenLayers.Layer.Yahoo(
			"Yahoo Satellite",
			{'type': YAHOO_MAP_SAT, 'sphericalMercator': true}
		);
		var yahoohyb = new OpenLayers.Layer.Yahoo(
			"Yahoo Hybrid",
			{'type': YAHOO_MAP_HYB, 'sphericalMercator': true}
		);

                var furcata_garp_nao = new OpenLayers.Layer.WMS(
                    "Furcata GARP Não",
                    "http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_furcata_garp_nao.map",
                    {
                        layers: "furcata_garp_nao",
                        styles: '',
                        srs: 'EPSG:4269',
                        format: 'image/png',
                        tiled: 'true',
                        transparent: true
                    },
                    {
                        'opacity': 0.75,
                        'isBaseLayer': false,
                        'wrapDateLine': true
                    }
                );

                var furcata_garp_sim = new OpenLayers.Layer.WMS(
                    "Furcata GARP Sim",
                    "http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_furcata_garp_sim.map",
                    {
                        layers: "furcata_garp_sim",
                        styles: '',
                        srs: 'EPSG:4269',
                        format: 'image/png',
                        tiled: 'true',
                        transparent: true
                    },
                    {
                        'opacity': 0.75,
                        'isBaseLayer': false,
                        'wrapDateLine': true
                    }
                );

		var vectors = new OpenLayers.Layer.Vector(
			"Marcadores",
			{isBaseLayer: false}
		);

		// adiciona as Layers no Mapa Após do Algoritmo garp
		map.addLayers([ gphy,
						gmap,
						ghyb,
						gsat,
						yahoo,                  //não suporta zoom > 15
						yahoohyb,		//não suporta zoom > 15
						yahoosat,		//não suporta zoom > 15
						furcata_garp_nao,
                                                furcata_garp_sim,
						vectors]);

//		var info = new OpenLayers.Control.WMSGetFeatureInfo({
//			url: "http://127.0.0.1:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_postgis.map",
//			title: 'Identify features by clicking',
//			queryVisible: true,
//			vendorParams: {
//				"FEATURE_COUNT": "1000"},
//			eventListeners: {
//				getfeatureinfo:
//					function(event) {
//					if((event.text).length != 1) {
//						map.addPopup(new OpenLayers.Popup.FramedCloud(
//						"chicken",
//						map.getLonLatFromPixel(event.xy),
//						null,
//						event.text,
//						null,
//						true
//					));
//					}
//				}
//			}
//		});
//		map.addControl(info);
//		info.activate();

		var report = function(e) {
			OpenLayers.Console.log(e.type, e.feature.id);
		};

		var highlightCtrl = new OpenLayers.Control.SelectFeature(vectors, {
			hover: true,
			highlightOnly: true,
			renderIntent: "temporary",
			eventListeners: {
				beforefeaturehighlighted: report,
				featurehighlighted: report,
				featureunhighlighted: report
			}
		});

		var selectCtrl = new OpenLayers.Control.SelectFeature(vectors,
			{clickout: true}
		);

		map.events.register("click", map,
		function(e) {
			// Read the map coordinates from the click event
			var lonlat = map.getLonLatFromViewPortPx(e.xy).transform(map.projection,map.displayProjection);
			// Construct the query URL
			var url = "ClickQueryAfterGarp.php";
			url += "?lon=" + lonlat.lon;
			url += "&lat=" + lonlat.lat;

			// Load the URL into an iframe
			document.getElementById("query").src = url;
		});

		map.addControl(highlightCtrl);
		map.addControl(selectCtrl);
		map.addControl(new OpenLayers.Control.EditingToolbar(vectors));
		//map.addControl(new OpenLayers.Control.Scale($('scale')));
		map.addControl(new OpenLayers.Control.MousePosition({div: document.getElementById("location")}));
		map.addControl(new OpenLayers.Control.KeyboardDefaults);
		var panel = new OpenLayers.Control.Panel(
			{div: document.getElementById("panel")}
		);
		map.addControl(panel);
		var history = new OpenLayers.Control.NavigationHistory();
		map.addControl(history);
		panel.addControls(
			[history.next,
				history.previous]
		);

                var longitude = -50.021439;
                var latitude = -22.679066;
                var zoom = 3;
		map.setCenter(new OpenLayers.LonLat(longitude, latitude).transform(map.displayProjection, map.projection), zoom);
		highlightCtrl.activate();
		selectCtrl.activate();

		// Mapa Antes do ALgoritmo
		var map_before_garp;
		var options_before_garp = {
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
			// map horizontal units are meters
			units: "m",
			// this resolution displays the globe in one 256x256 pixel tile
			maxResolution: 156543.0339,
			// these are the bounds of the globe in sperical mercator
			maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
			20037508, 20037508),
			controls: [new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar()]
		};

		map_before_garp = new OpenLayers.Map('map_before_garp', options_before_garp);
		map_before_garp.addControl(new OpenLayers.Control.LayerSwitcher());

		// cria as Layers do Google Maps
		var gphy_before_garp = new OpenLayers.Layer.Google(
			"Google Physical",
			{type: G_PHYSICAL_MAP,'sphericalMercator': true}
		);
		var gmap_before_garp = new OpenLayers.Layer.Google(
			"Google Street", // the default
			{'sphericalMercator': true}
		);
		var ghyb_before_garp = new OpenLayers.Layer.Google(
			"Google Hybrid",
			{type: G_HYBRID_MAP,'sphericalMercator': true}
		);
		var gsat_before_garp = new OpenLayers.Layer.Google(
			"Google Satellite",
			{type: G_SATELLITE_MAP,'sphericalMercator': true}
		);

                // cria as Layers do Yahoo! Maps
		var yahoo_before_garp = new OpenLayers.Layer.Yahoo(
			"Yahoo Street",
			{'sphericalMercator': true}
		);
		var yahoosat_before_garp = new OpenLayers.Layer.Yahoo(
			"Yahoo Satellite",
			{'type': YAHOO_MAP_SAT, 'sphericalMercator': true}
		);
		var yahoohyb_before_garp = new OpenLayers.Layer.Yahoo(
			"Yahoo Hybrid",
			{'type': YAHOO_MAP_HYB, 'sphericalMercator': true}
		);

                var furcata_original = new OpenLayers.Layer.WMS(
                    "Furcata GARP",
                    "http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_furcata_original.map",
                    {
                        layers: "furcata_original",
                        styles: '',
                        srs: 'EPSG:4269',
                        format: 'image/png',
                        tiled: 'true',
                        transparent: true
                    },
                    {
                        'opacity': 0.75,
                        'isBaseLayer': false,
                        'wrapDateLine': true
                    }
                );

		var vectors_before_garp = new OpenLayers.Layer.Vector(
			"Marcadores",
			{isBaseLayer: false}
		);

		// adiciona as Layers no Mapa Antes do Algoritmo garp
		map_before_garp.addLayers([  gphy_before_garp,
                                             gmap_before_garp,
                                             ghyb_before_garp,
                                             gsat_before_garp,
                                             yahoo_before_garp,
                                             yahoosat_before_garp,
                                             yahoohyb_before_garp,
                                             furcata_original,
                                             vectors_before_garp]);

		var report_before_garp = function(e) {
			OpenLayers.Console.log(e.type, e.feature.id);
		};
		var highlightCtrl_before_garp = new OpenLayers.Control.SelectFeature(vectors_before_garp, {
			hover: true,
			highlightOnly: true,
			renderIntent: "temporary",
			eventListeners: {
				beforefeaturehighlighted: report_before_garp,
				featurehighlighted: report_before_garp,
				featureunhighlighted: report_before_garp
			}
		});

		var selectCtrl_before_garp = new OpenLayers.Control.SelectFeature(vectors_before_garp,
			{clickout: true}
		);

		map_before_garp.events.register("click", map_before_garp,
		function(e) {
			// Read the map coordinates from the click event
			var lonlat_before_garp = map_before_garp.getLonLatFromViewPortPx(e.xy).transform(map_before_garp.projection,map_before_garp.displayProjection);

			// Construct the query URL
			var url_before_garp = "ClickQueryBeforeGarp.php";
			url_before_garp += "?lon=" + lonlat_before_garp.lon;
			url_before_garp += "&lat=" + lonlat_before_garp.lat;

			// Load the URL into an iframe
			document.getElementById("query_before_garp").src = url_before_garp;
		});
		map_before_garp.addControl(highlightCtrl_before_garp);
		map_before_garp.addControl(selectCtrl_before_garp);
		map_before_garp.addControl(new OpenLayers.Control.EditingToolbar(vectors_before_garp));
		//map_before_garp.addControl(new OpenLayers.Control.Scale($('scale')));
		map_before_garp.addControl(new OpenLayers.Control.MousePosition({div: document.getElementById("location_before_garp")}));
		map_before_garp.addControl(new OpenLayers.Control.KeyboardDefaults);
		var panel_before_garp = new OpenLayers.Control.Panel(
			{div: document.getElementById("panel_before_garp")}
		);
		map_before_garp.addControl(panel_before_garp);
		var history_before_garp = new OpenLayers.Control.NavigationHistory();
		map_before_garp.addControl(history_before_garp);
		panel_before_garp.addControls(
			[history_before_garp.next,
				history_before_garp.previous]
		);
		var longitude_before_garp	= longitude;
		var latitude_before_garp	= latitude
		var zoom_before_garp		= zoom;
		map_before_garp.setCenter(new OpenLayers.LonLat(longitude_before_garp, latitude_before_garp).transform(map_before_garp.displayProjection, map_before_garp.projection), zoom_before_garp);
		highlightCtrl_before_garp.activate();
		selectCtrl_before_garp.activate();
	}
</script>

<div id="back"></div>

<table>
	<tr>
		<td>
			<div id="first_map">
				<h1 class="application">Aplicação Antes do Algoritmo <i>GARP</i></h1>
				<div id="map_before_garp"></div>
				<div id="location_before_garp" class="location">location</div>
				<div id="panel_before_garp"></div>
				<iframe id="query_before_garp"></iframe>
			</div>
		</td>
		<td>
			<div id="second_map">
				<h1 class="application">Aplicação Após Algoritmo <i>GARP</i></h1>
				<div id="map"></div>
				<div id="location" class="location">location</div>
				<?php
					// local em que os arquivos de entrada e saída ficam armazenados
					$context_path							= "C:\\\\Program Files\\\\openModeller\\\\examples\\\\";
					// obtém os dados de entrada do algoritmo via HTTP POST Response
					$species_name                                                   = $_POST['species_name'];
					$file_name_original_species_map                                 = GetFileName($_POST['file_original_species_map']);
					$file_original_species_map                                      = $context_path . $_POST['file_original_species_map'];
					// arquivo de saída: Mapa de Produtividade após a aplicação do algoritmo garp
					$file_name_output						= "testeOGC.txt";
					$file_output							= $context_path . $file_name_output;

					// armazena os dados de entrada no Banco de Dados Espacial
					$schema_name = "garp";
					$sql_create_schema = "DROP SCHEMA IF EXISTS " . $schema_name . " CASCADE;" . " "
										      .	"CREATE SCHEMA garp
											 AUTHORIZATION postgres;";
					// armazena os dados de entrada do Mapa de Ocorrências fornecidos pelo usuário
					$furcata_original_table_name = "furcata_original";
					$sql_create_furcata_original_table = "CREATE TABLE " . $schema_name . "." . $furcata_original_table_name . " "
                                                                                                            . "(
                                                                                                                    foid integer,
                                                                                                                    label varchar,
                                                                                                                    longitude double precision,
                                                                                                                    latitude double precision,
                                                                                                                    abundance integer
														)
														WITHOUT OIDS;";
					// copia os dados de entrada do Mapa de Ocorrências no formato padrão .TXT para o Banco de Dados Geoespacial
					// remove o cabeçalho de descrição dos campos para o arquivo de entrada do Mapa de Contorno
                                        removeLines($file_original_species_map, 1);
					$sql_copy_furcata_original_txt_to_bd = "COPY " . $schema_name . "." . $furcata_original_table_name . " "
													 . "FROM " . "'" . $file_original_species_map . "'" . ";";
					// adiciona a coluna ID à tabela de Mapa de Ocorrências
					$sql_add_furcata_original_id_column = "ALTER TABLE " . $schema_name . "." . $furcata_original_table_name                                    . " "
													    . "ADD COLUMN id serial NOT NULL;"                                      . " "
													    . "ALTER TABLE " . $schema_name . "." . $furcata_original_table_name    . " "
													    . "ADD CONSTRAINT furcata_original_pkey PRIMARY KEY (id);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Ocorrências
					$furcata_original_geometry_column_name	= "thepoint_lonlat";
					$furcata_original_spatial_reference_id	= 4269;
					$furcata_original_type                  = "POINT";
					$furcata_original_dimension		= 2;
					$sql_add_furcata_original_geometry_column = "SELECT AddGeometryColumn( "
														  . "'" . $schema_name						. "'" . ", "
														  . "'" . $furcata_original_table_name                  	. "'" . ", "
														  . "'" . $furcata_original_geometry_column_name                . "'" . ", "
															. $furcata_original_spatial_reference_id                      . ", "
														  . "'" . $furcata_original_type                                . "'" . ", "
															. $furcata_original_dimension				      . " );";
					// preenche a coluna THEPOINT_LONLAT na tabela de Mapa de Ocorrências
					$sql_set_values_into_furcata_original_geometry_column = "UPDATE " . $schema_name . "." . $furcata_original_table_name											. " "
                                                                                                                               . "SET " . $furcata_original_geometry_column_name															. " "
                                                                                                                               . "= setsrid(makepoint(longitude, latitude), " . $furcata_original_spatial_reference_id . ");"			. " "
                                                                                                                               . "CREATE INDEX idx_furcata_original_thepoint_lonlat ON " . $schema_name . "." . $furcata_original_table_name    . " "
                                                                                                                               . "USING GIST (" . $furcata_original_geometry_column_name . ");";

					// cria o arquivo 'request' para a execução do GARP
                                        $path = "C:\\Program Files\\openModeller\\examples\\request.txt";
                                        $request_txt = fopen($path,"w");
                                        $request_content = 'WKT Coord System = GEOGCS["WGS84", DATUM["WGS84", SPHEROID["WGS84", 6378137.0, 298.257223563]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Longitude",EAST], AXIS["Latitude",NORTH]]';
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Occurrences source = ". $file_name_original_species_map .".txt";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Occurrences group = ". $species_name;
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Map = rain_coolest.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Map = temp_avg.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Mask = rain_coolest.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output format = rain_coolest.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output map = rain_coolest.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output map = temp_avg.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output mask = rain_coolest.tif";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output model = furcata.xml";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output file = furcata.img";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Output file type = ByteHFA";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Algorithm = DG_GARP";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = MaxGenerations 100";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = ConvergenceLimit 0.05";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = PopulationSize 50";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = Resamples 2500";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = MutationRate 0.25";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "\r\n";
                                        fwrite($request_txt, $request_content);

                                        $request_content = "Parameter = CrossoverRate 0.25";


                                        if (fwrite($request_txt, $request_content) === FALSE) {
                                            echo "Cannot write to file ($request_txt)";
                                            exit;
                                        }
                                        fclose($request_txt);

                                        $comando = '"C:\Program Files\openModeller\om_console.exe" "C:\Program Files\openModeller\examples\request.txt"';
                                        
                                        // executa o algoritmo GARP
					$output_garp_algorithm = shell_exec($comando);

					// armazena os dados gerados pelo algoritmo GARP no Banco de Dados Espacial
					$furcata_garp_table_name = "furcata_garp";
					$sql_create_furcata_garp_table = "CREATE TABLE " . $schema_name . "." . $furcata_garp_table_name
                                                                                                              . "(
                                                                                                                     longitude double precision,
                                                                                                                     latitude double precision,
                                                                                                                     abundance integer
                                                                                                                  )
                                                                                                                  WITHOUT OIDS;";
					// copia os dados de saída no formato padrão .TXT TABULADO para o Banco de Dados Geoespacial
					$sql_copy_file_output_txt_to_bd = "COPY " . $schema_name . "." . $furcata_garp_table_name . " "
																  . "FROM " . "'" . $file_output . "'" . ";";
					// adiciona a coluna ID à tabela de Mapa de Ocorrências Após o GARP
					$sql_add_furcata_garp_id_column = "ALTER TABLE " . $schema_name . "." . $furcata_garp_table_name                                       . " "
                                                                                                              . "ADD COLUMN id serial NOT NULL;"                               . " "
                                                                                                              . "ALTER TABLE " . $schema_name . "." . $furcata_garp_table_name . " "
                                                                                                              . "ADD CONSTRAINT furcata_garp_pkey PRIMARY KEY (id);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Ocorrências Após o GARP
					$furcata_garp_geometry_column_name	= "thepoint_lonlat";
					$furcata_garp_spatial_reference_id	= 4269;
					$furcata_garp_type			= "POINT";
					$furcata_garp_dimension			= 2;
					$sql_add_furcata_garp_geometry_column	= "SELECT AddGeometryColumn("
                                                                                                              . "'" . $schema_name                                  . "'" . ", "
                                                                                                              . "'" . $furcata_garp_table_name                      . "'" . ", "
                                                                                                              . "'" . $furcata_garp_geometry_column_name            . "'" . ", "
                                                                                                                    . $furcata_garp_spatial_reference_id                  . ", "
                                                                                                              . "'" . $furcata_garp_type                            . "'" . ", "
                                                                                                                    . $furcata_garp_dimension                             . ");";
					// preenche a coluna THEPOINT_LONLAT na tabela de Mapa de Ocorrências Após GARP (dados georeferenciados de saída)
 					$sql_set_values_into_furcata_garp_geometry_column = "UPDATE " . $schema_name . "." . $furcata_garp_table_name                                                                               . " "
                                                                                                                           . "SET " . $furcata_garp_geometry_column_name                                                            . " "
                                                                                                                           . "= setsrid(makepoint(longitude, latitude), " . $furcata_garp_spatial_reference_id . ");"               . " "
                                                                                                                           . "CREATE INDEX idx_furcata_garp_thepoint_lonlat ON " . $schema_name . "." . $furcata_garp_table_name    . " "
                                                                                                                           . "USING GIST (" . $furcata_garp_geometry_column_name . ");";
					// cria duas tabelas-filhas da TABLE furcata_garp, separando as ocorrências positivas das negativas
                                        // armazena os dados do Mapa de Ocorrências Sim Após GARP
					$furcata_garp_sim_table_name = "furcata_garp_sim";
					$sql_create_furcata_garp_sim_table = "CREATE TABLE " . $schema_name . "." . $furcata_garp_sim_table_name . " "
                                                                                                                . "(
                                                                                                                        longitude double precision,
                                                                                                                        latitude double precision,
                                                                                                                        abundance integer
                                                                                                                    )
                                                                                                                    WITHOUT OIDS;";
					// armazena os dados do Mapa de Ocorrências Não Após GARP
                                        $furcata_garp_nao_table_name = "furcata_garp_nao";
					$sql_create_furcata_garp_nao_table = "CREATE TABLE " . $schema_name . "." . $furcata_garp_nao_table_name . " "
                                                                                                                . "(
                                                                                                                        longitude double precision,
                                                                                                                        latitude double precision,
                                                                                                                        abundance integer
                                                                                                                    )
                                                                                                                    WITHOUT OIDS;";
					// adiciona a coluna ID à tabela de Mapa de Ocorrências Sim Após GARP
					$sql_add_furcata_garp_sim_id_column = "ALTER TABLE " . $schema_name . "." . $furcata_garp_sim_table_name                                    . " "
                                                                                                                . "ADD COLUMN id serial NOT NULL;"                                          . " "
                                                                                                                . "ALTER TABLE " . $schema_name . "." . $furcata_garp_sim_table_name    . " "
                                                                                                                . "ADD CONSTRAINT furcata_garp_sim_pkey PRIMARY KEY (id);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Ocorrências Sim Após GARP
					$furcata_garp_sim_geometry_column_name    = "thepoint_lonlat";
					$furcata_garp_sim_spatial_reference_id    = 4269;
					$furcata_garp_sim_type                    = "POINT";
					$furcata_garp_sim_dimension               = 2;
					$sql_add_furcata_garp_sim_geometry_column = "SELECT AddGeometryColumn( "
														  . "'" . $schema_name						. "'" . ", "
														  . "'" . $furcata_garp_sim_table_name                  	. "'" . ", "
														  . "'" . $furcata_garp_sim_geometry_column_name            . "'" . ", "
															. $furcata_garp_sim_spatial_reference_id                  . ", "
														  . "'" . $furcata_garp_sim_type                            . "'" . ", "
															. $furcata_garp_sim_dimension                             . " );";
					// adiciona a coluna ID à tabela de Mapa de Ocorrências Não Após GARP
					$sql_add_furcata_garp_nao_id_column = "ALTER TABLE " . $schema_name . "." . $furcata_garp_nao_table_name                                    . " "
                                                                                                                . "ADD COLUMN id serial NOT NULL;"                                          . " "
                                                                                                                . "ALTER TABLE " . $schema_name . "." . $furcata_garp_nao_table_name    . " "
                                                                                                                . "ADD CONSTRAINT furcata_garp_nao_pkey PRIMARY KEY (id);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Ocorrências Não Após GARP
					$furcata_garp_nao_geometry_column_name    = "thepoint_lonlat";
					$furcata_garp_nao_spatial_reference_id    = 4269;
					$furcata_garp_nao_type                    = "POINT";
					$furcata_garp_nao_dimension               = 2;
					$sql_add_furcata_garp_nao_geometry_column = "SELECT AddGeometryColumn( "
														  . "'" . $schema_name						. "'" . ", "
														  . "'" . $furcata_garp_nao_table_name                  	. "'" . ", "
														  . "'" . $furcata_garp_nao_geometry_column_name            . "'" . ", "
															. $furcata_garp_nao_spatial_reference_id                  . ", "
														  . "'" . $furcata_garp_nao_type                            . "'" . ", "
															. $furcata_garp_nao_dimension                             . " );";
					// inserir dados na tabela de Mapa de Ocorrências Sim Após GARP
					$sql_set_values_into_furcata_garp_sim = "INSERT INTO " . $schema_name . "." . $furcata_garp_sim_table_name . " " . "(longitude, latitude, abundance, id, " . $furcata_garp_sim_geometry_column_name . ")" . " "
                                                                                                                        . "SELECT " . "longitude, latitude, abundance, id, " . $furcata_garp_sim_geometry_column_name                                      . " "
                                                                                                                        . "FROM " . $schema_name . "." . $furcata_garp_table_name                                                                                       . " "
                                                                                                                        . "WHERE " . $schema_name . "." . $furcata_garp_table_name . "." . "abundance" . " " . "= 1;"                                                   . " "
                                                                                                                        . "CREATE INDEX idx_furcata_garp_sim_thepoint_lonlat ON " . $schema_name . "." . $furcata_garp_sim_table_name                               . " "
                                                                                                                        . "USING GIST (" . $furcata_garp_sim_geometry_column_name . ");";
					// inserir dados na tabela de Mapa de Ocorrências Não Após GARP
					$sql_set_values_into_furcata_garp_nao = "INSERT INTO " . $schema_name . "." . $furcata_garp_nao_table_name . " " . "(longitude, latitude, abundance, id, " . $furcata_garp_nao_geometry_column_name . ")"  . " "
                                                                                                                        . "SELECT " . "longitude, latitude, abundance, id, " . $furcata_garp_nao_geometry_column_name                                       . " "
                                                                                                                        . "FROM " . $schema_name . "." . $furcata_garp_table_name                                                                                        . " "
                                                                                                                        . "WHERE " . $schema_name . "." . $furcata_garp_table_name . "." . "abundance" . " " . "= 0;"                                                    . " "
                                                                                                                        . "CREATE INDEX idx_furcata_garp_nao_thepoint_lonlat ON " . $schema_name . "." . $furcata_garp_nao_table_name                                . " "
                                                                                                                        . "USING GIST (" . $furcata_garp_nao_geometry_column_name . ");";

					// executa os scripts para armazzenar os dados de entrada e os dados de saída gerados pelo algoritmo Filetring
					$database = pg_connect("dbname=postgis user=postgres password=tcc09")
								or die("Não foi possível estabelecer conexão ao Banco da Dados.");
					pg_query($database, $sql_create_schema);
					pg_query($database, $sql_create_furcata_original_table);
					pg_query($database, $sql_copy_furcata_original_txt_to_bd);
					pg_query($database, $sql_add_furcata_original_id_column);
					pg_query($database, $sql_add_furcata_original_geometry_column);
					pg_query($database, $sql_set_values_into_furcata_original_geometry_column);
					pg_query($database, $sql_create_furcata_garp_table);
					pg_query($database, $sql_copy_file_output_txt_to_bd);
					pg_query($database, $sql_add_furcata_garp_id_column);
					pg_query($database, $sql_add_furcata_garp_geometry_column);
					pg_query($database, $sql_set_values_into_furcata_garp_geometry_column);
                                        pg_query($database, $sql_create_furcata_garp_sim_table);
                                        pg_query($database, $sql_create_furcata_garp_nao_table);
                                        pg_query($database, $sql_add_furcata_garp_sim_id_column);
                                        pg_query($database, $sql_add_furcata_garp_sim_geometry_column);
                                        pg_query($database, $sql_add_furcata_garp_nao_id_column);
                                        pg_query($database, $sql_add_furcata_garp_nao_geometry_column);
                                        pg_query($database, $sql_set_values_into_furcata_garp_sim);
                                        pg_query($database, $sql_set_values_into_furcata_garp_nao);
					pg_close($database);

					// Custom Functions
					function removeLines($txtfile, $numlines)  {
						if (file_exists("temp.txt"))
							unlink("temp.txt");
						$arrayz = file("$txtfile");
						$tempWrite = fopen("temp.txt", "w");
						for ($i = $numlines; $i < count($arrayz); $i++)
							fputs($tempWrite, "$arrayz[$i]");
						fclose($tempWrite);
						copy("temp.txt", "$txtfile");
						unlink("temp.txt");
					}

					function GetFileName($filepath) {
						preg_match('/[^?]*/', $filepath, $matches);
						$string = $matches[0];
						#split the string by the literal dot in the filename
						$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
						#get the last dot position
						$lastdot = $pattern[count($pattern)-1][1];
						#now extract the filename using the basename function
						$filename = basename(substr($string, 0, $lastdot-1));
						#return the filename part
						return $filename;
					}
				?>
				<div id="panel"></div>
				<iframe id="query"></iframe>
			</div>
	   </td>
	</tr>
</table>